<?php

namespace App\Console\Commands;

use App\Enum\OrderEnum;
use App\Models\OrderModel;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Symfony\Component\Console\Output\ConsoleOutput;

class ModifyOrderAppraiseCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:auto-appraise {debug?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '修改订单评价状态为已评价';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle(ConsoleOutput $output)
    {
        $output->writeln('===========修改订单评价状态为已评价开始===========');

        $pendingOrder = OrderModel::query()->where('is_appraise', '=', 0)->where('status',OrderEnum::STATUS_SUCCESS)->where('created_at', '<=', Carbon::now()->subDays(15)->timestamp)->get();

        if($pendingOrder->isEmpty()){
            $output->writeln('没有待评价的订单');
        }
        try {
            //修改订单评价状态为已评价
            DB::beginTransaction();
            foreach ($pendingOrder->toArray() as $item){
                OrderModel::query()->where('id', $item['id'])->update(['is_appraise' => 1]);

                //已经评价过的,不在生成评价
                $appraise = DB::table('appraise')->where('order_id', $item['id'])->first();
                if($appraise){
                    continue;
                }
                //评价内容默认5星好评
                $data = [
                    'order_id' => $item['id'],
                    'user_id' => $item['user_id'],
                    'driver_id' => $item['driver_id'],
                    'words_appraise' => '非常好',
                    'label_tag' => '礼貌友好,服务周到,驾驶平稳,车辆整洁,准时到达',
                    'appraise' => 5,
                    'created_at' => time(),
                    'updated_at' => time(),
                ];
                DB::table('appraise')->insert($data);
            }
            DB::commit();
            $output->writeln('===========修改订单评价状态为已评价结束===========');
        }catch (\Exception $e){
            DB::rollBack();
            $output->writeln('修改订单评价状态为已评价失败:'.$e->getMessage());
        }
    }
}
